package city.spring.configure.security.handler;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.oauth2.provider.error.OAuth2AccessDeniedHandler;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 自定义访问拒绝处理程序。
 * 使用安全程序Security进行授权的时候，当权限不足的时候，因权限不足不允许访问的时候，会抛出 AccessDeniedException 异常，
 * 该异常会被 @RestControllerAdvice 捕获处理，因此，如果设置全局统一异常处理（@RestControllerAdvice）则该异常不会走这个对象来处理异常信息
 *
 * @author HouKunLin
 * @date 2019/12/1 0001 21:54
 */
@Component
public class CustomAccessDeniedHandler implements AccessDeniedHandler {
    private static final Logger logger = LoggerFactory.getLogger(CustomAccessDeniedHandler.class);
    private final AccessDeniedHandler accessDeniedHandler = new OAuth2AccessDeniedHandler();

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException e) throws IOException, ServletException {
        logger.error("OAuth2 错误 -> 自定义访问拒绝处理程序：{}", e.getMessage());
        accessDeniedHandler.handle(request, response, e);
       /* response.setStatus(HttpStatus.UNAUTHORIZED.value());
        response.setContentType("application/json; charset=UTF-8");
        HashMap<String, Object> map = new HashMap<>(16);
        map.put("msg", e.getMessage());
        map.put("type", e.getClass().getName());
        map.put("message", "拒绝访问异常");
        response.getWriter().write(objectMapper.writeValueAsString(map));*/
    }

    @PostConstruct
    public void postConstruct() {
        logger.debug("自定义访问拒绝处理程序: {}", this);
    }
}
